<template>
   <div class="pie-chart">
    <img v-if="isDesigner" :src="imgSrc" alt="" style="width: 200px">
    <div v-else class="pie-chart__chart" ref="chart" :style="{ width: chartTransWidth, height: chartTransHeight }"></div>
  </div>
</template>

<script>
import { isEmpty } from "lodash"
import { loadRoute3Path } from '@/utils/loadRemote'
export default {
  name: 'pie',
  props: {
    value: null,
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    pieLists: {
      type: Array,
      default: () => []
    },
    chartWidth: {
      type: Number,
      default: 200
    },
    chartHeight: {
      type: Number,
      default: 100
    },
  },
  data() {
    return {
      initLists: [{name: "Mon", value: "150"},{name: "Tue", value: "230"},{name: "Wed", value: "224"},{name: "Thu", value: "218"},{name: "Fri", value: "135"}],
      myChart: null,
      imgSrc: require("@/icons/svg/pie.jpg")
    }
  },
  mounted() {
    if (!this.isDesigner) {
      this.drawChart()
    }
  },
  computed: {
    isDesigner() {
      return this.$attrs._source === 'designer'
    },
    mixEditable() {
      return !(this.$attrs.readonly || this.$attrs.disabled) && this.mode === "edit"
    },
    lists() {
     return this.isDesigner ? this.initLists : isEmpty(this.pieLists) ? this.initLists : this.pieLists
    },
    chartTransWidth() {
      return this.chartWidth + 'px'
    },
    chartTransHeight() {
      return this.chartHeight + 'px'
    },
    prixPath() {
      return loadRoute3Path('')
    }
  },
  methods: {
    drawChart() {
      if (typeof window.echarts === 'function') {
        this.initEcharts()
      } else {
        const pre_static = loadRoute3Path('')
        const script = document.createElement('script')
        script.src = `${pre_static}/static/js/echarts.js`
        script.onload = this.initEcharts.bind(this)
        document.head.appendChild(script)
      }
      // const { Echarts } = components
      // const chart = Echarts.init(this.$refs.chart);
      
      // chart.setOption(option);
    },
    initEcharts() {
				setTimeout(() => {
          const el = this.$refs.chart
					this.myChart = echarts.init(el, '')
          const option = this.isDesigner ? this.initLists : {
            tooltip: {
              trigger: 'item',
              formatter: "{b} : {c} ({d}%)"
            },
            series: [
              {
                type: "pie",
                data: this.lists,
                zlevel: 1,
                z: 1
              },
            ],
          };
					this.myChart.setOption(option)
				})
				window.addEventListener('resize', () => {
					this.myChart.resize()
				});
			},
  }
};
</script>
<style lang="scss" scoped>
.pie-chart {
  width: 100%;
  z-index: 1000;
}
</style>
